package com.gravata.enigma.activities;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.Button;
import android.widget.ListView;

import com.gravata.enigma.R;
import com.gravata.enigma.ReloadDataListener;
import com.gravata.enigma.adapter.ProfileAdapter;
import com.gravata.enigma.model.Profile;

public class ListaProfile extends ListActivity {

	private final int REQUEST_EDIT=91;
	private final int REQUEST_INSERT=90;
	private int RESULTCODE=0;
	private Context context=this;
	private ProfileAdapter profileAdapter;

	private List<Profile> selecionados;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile_lista);

		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		profileAdapter=new ProfileAdapter(this, TelaInicial.repositorioProfile.listar(),dataListener);
		setListAdapter(profileAdapter);

		Button btnAdd=(Button) findViewById(R.id.profile_add);
		btnAdd.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent=new Intent(context,ProfileActivity.class);
					startActivityForResult(intent, REQUEST_INSERT);
				}
			});


		ListView listView = getListView();
 		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
 		listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

 			private int count=0;

 		    @Override
 		    public void onItemCheckedStateChanged(ActionMode mode, int position,
 		                                          long id, boolean checked) {
 		        // Here you can do something when items are selected/de-selected,
 		        // such as update the title in the CAB
 		    	count=checked?count+1:count-1;
 		    	mode.setTitle(count+"");

 		    	profileAdapter.setSelection(position, checked);
 		    }


 		    @Override
 		    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
 		        // Respond to clicks on the actions in the CAB
 		        switch (item.getItemId()) {
 		            case R.id.profile_apagar:

					try {
						TelaInicial.repositorioProfile.excluir(getSelecionados());
						profileAdapter.clearSelection();
 		            	count=0;
 		                mode.finish(); // Action picked, so close the CAB
 		                profileAdapter.setData(TelaInicial.repositorioProfile.listar());
 		                TelaInicial.profile=TelaInicial.repositorioProfile.getSelecionado();
 		                RESULTCODE=10;
					} catch (SQLException e) {
						e.printStackTrace();
					}


 		                return true;
 		            default:
 		                return false;
 		        }
 		    }

 		    @Override
 		    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
 		        // Inflate the menu for the CAB
 		        MenuInflater inflater = mode.getMenuInflater();
 		        inflater.inflate(R.menu.profile_lista, menu);

 		        return true;
 		    }

 		    @Override
 		    public void onDestroyActionMode(ActionMode mode) {
 		        // Here you can make any necessary updates to the activity when
 		        // the CAB is removed. By default, selected items are deselected/unchecked.
 		    	count=0;
 		    	profileAdapter.clearSelection();
 		    }

 		    @Override
 		    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
 		        // Here you can perform updates to the CAB due to
 		        // an invalidate() request
 		        return false;
 		    }
 		});


	}

	private ReloadDataListener dataListener=new ReloadDataListener() {

		@Override
		public void onReloadData() {
			RESULTCODE=10;
		}

		@Override
		public void onFealoadData(List<?> list) {

		}
	};

	   private List<Profile> getSelecionados(){
	    	selecionados=new ArrayList<Profile>();
	    	SparseBooleanArray checked = getListView().getCheckedItemPositions();
	    	int size = checked.size(); // number of name-value pairs in the array
	    	for (int i = 0; i < size; i++) {
	    	    int key = checked.keyAt(i);
	    	    boolean value = checked.get(key);
	    	    if(value){
	    	    	selecionados.add(profileAdapter.getItem(key));
	    	    }
	    	}
	    	return selecionados;
	    }

	   @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		   switch (item.getItemId()) {

		   case android.R.id.home:
			   setResult(RESULTCODE);
			   finish();
		   }
		   return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		setResult(RESULTCODE);
		super.onBackPressed();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Profile profile=profileAdapter.getItem(position);

		Intent intent=new Intent(this,ProfileActivity.class);
		intent.putExtra("profile",profile);

		startActivityForResult(intent, REQUEST_EDIT);

	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode==1){
			RESULTCODE=1;
			profileAdapter.setData(TelaInicial.repositorioProfile.listar());
		}

		setResult(resultCode);
		super.onActivityResult(requestCode, resultCode, data);
	}

}
